<?php

namespace Managers;

class Rss extends \Lib\Model\DoctrineManager{
    
    public function getRss($site, $count) {   
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('r')
                ->from('Entities\Rss', 'r')
                ->where('r.site = :site')
                ->setParameter('site', $site)
                ->setMaxResults($count)
                ->orderBy('r.date', 'DESC');
        $result = $qb->getQuery()->getResult();
        return $result;
    }

    public function addRss($data) {
        $em = $this->getEntityManager();
        $em->getConnection()->beginTransaction();
        
        try {
           foreach ($data as $key => $value) {
               $rss = new \Entities\Rss();
               $rss->setTitle($data[$key]['title']);
               $rss->setSite($data[$key]['site']);
               $rss->setDescription($data[$key]['description']);
               $rss->setLink($data[$key]['link']);
               $now = new \DateTime();
               $dateTime = new \DateTime();
               $dateTime->setTimestamp($data[$key]['date']->get());
               $rss->setDate($dateTime);
               $rss->setCreatedAt($now);
               $em->persist($rss);
           }
            $em->flush();
            $em->getConnection()->commit();
        } catch (Exception $e) {
            $em->getConnection()->rollback();
        }
    }

    public function clear() {
        $em = $this->getEntityManager();
        $entities = $em->getRepository('Entities\Rss')->findAll();
            foreach ($entities as $entity) {
                $em->remove($entity);
            }
        $em->flush();
    }

}